package com.yiqi.news.mvp.ui.activity

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.BottomSheetDialog
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import butterknife.OnClick

import com.jess.arms.base.BaseActivity
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.ArmsUtils
import com.jess.arms.widget.DividerItemDecoration
import com.novel.cn.ext.dp2px
import com.yiqi.huize.loadImage

import com.yiqi.news.di.component.DaggerUserinfoComponent
import com.yiqi.news.di.module.UserinfoModule
import com.yiqi.news.mvp.contract.UserinfoContract
import com.yiqi.news.mvp.presenter.UserinfoPresenter

import com.yiqi.news.R
import com.yiqi.news.app.widget.qmui.QMUITipDialog
import com.yiqi.news.entity.User
import com.yiqi.news.mvp.ui.adapter.DialogAdapter
import com.yiqi.news.mvp.ui.adapter.LabelAdapter
import kotlinx.android.synthetic.main.activity_userinfo.*
import kotlinx.android.synthetic.main.dialog_bottom_sheet_label.view.*
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.jess.arms.utils.RxClipboardTool
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.yiqi.huize.mvp.dialog.InputDialog
import com.yiqi.news.app.service.UserController
import com.yiqi.news.app.utils.DateUtils.toDateStr
import java.util.*

class UserinfoActivity : BaseActivity<UserinfoPresenter>(), UserinfoContract.View, OnTimeSelectListener {
    override fun showUpdateSuccess() {
        mPresenter?.getUser()
    }

    override fun onTimeSelect(date: Date?, v: View?) {

        mPresenter?.updateBirthday(toDateStr(date))
    }


    override fun showError(user: String) {
        showMessage(user)
    }

    override fun showUser(user: User) {
        iv_userinfo_avatar.loadImage(user.headImg)
        tv_userinfo_nick.text = user.nickName
        tv_userinfo_gender.text = if (user.sex == 1) "男" else "女"
        tv_userinfo_birthday.text = user.birthday
        tv_userinfo_invited.text = user.invitationCode
    }

    private lateinit var selectList: MutableList<LocalMedia>

    private lateinit var timePickerView: TimePickerView
    private val mAvatarDialog: BottomSheetDialog by lazy {
        return@lazy BottomSheetDialog(this)
    }
    private val mGenderDialog: BottomSheetDialog by lazy {
        return@lazy BottomSheetDialog(this)
    }

    private val mAvatarAdapter: DialogAdapter by lazy {
        return@lazy DialogAdapter()
    }
    private val mGenderAdapter: DialogAdapter by lazy {
        return@lazy DialogAdapter()
    }

    private val mInputDialog: InputDialog by lazy {
        return@lazy InputDialog(this)
    }


    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerUserinfoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .userinfoModule(UserinfoModule(this))
                .build()
                .inject(this)
    }

    private val mQMUIInfoDialog: QMUITipDialog by lazy {
        return@lazy QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
                .setTipWord(getString(R.string.dialog_copy_code_success))
                .create()
    }

    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_userinfo //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    override fun initData(savedInstanceState: Bundle?) {
        initBottomSheetDialog()
        initBottomSexDialog()
        initDatePicker()
    }

    override fun onStart() {
        super.onStart()
        mPresenter?.getUser()
    }

    override fun showMessage(message: String) {
        ArmsUtils.snackbarText(message)
    }

    override fun launchActivity(intent: Intent) {
        ArmsUtils.startActivity(intent)
    }

    override fun killMyself() {
        finish()
    }


    override fun initImmersionBar() {
        super.initImmersionBar()
        mImmersionBar.titleBar(R.id.toolbar).init()
    }


    @OnClick(R.id.tv_userinfo_nick, R.id.iv_userinfo_avatar, R.id.tv_userinfo_invited, R.id.tv_userinfo_birthday, R.id.tv_userinfo_gender)
    fun onClick(view: View) {
        when (view.id) {
            R.id.tv_userinfo_nick -> initInputDialog()
            R.id.iv_userinfo_avatar -> mAvatarDialog.show()
            R.id.iv_userinfo_avatar -> mAvatarDialog.show()
            R.id.tv_userinfo_gender -> mGenderDialog.show()
            R.id.tv_userinfo_invited -> {
                try {
                    RxClipboardTool.copyText(this, UserController.getInstance().loginResultCache.invitationCode)
                    mQMUIInfoDialog.show()
                } catch (e: Exception) {
                    e.printStackTrace()
                }

            }
            R.id.tv_userinfo_birthday -> timePickerView.show()
        }
    }

    private fun initInputDialog() {
        mInputDialog.setOnCommitListener(object : InputDialog.OnCommitListener {
            override fun onCommit(content: String) {
                mPresenter?.updateNick(content)
                mInputDialog.dismiss()
            }
        })
        mInputDialog.show()
        mInputDialog.setHint(if (tv_userinfo_nick.text.toString().isNullOrEmpty()) "请输入昵称" else tv_userinfo_nick.text.toString())
    }

    private fun initBottomSheetDialog() {
        var mAvatarView = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_sheet_label, null, false)
        mAvatarView.recycler_view.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(dp2px(4)))
        mAvatarView.tv_title.text = "更换头像"
        mAvatarAdapter.bindToRecyclerView(mAvatarView.recycler_view)
        var arrayAvatar = arrayOf("选择相册", "拍照")
        mAvatarAdapter.setNewData(arrayAvatar.toList())
        mAvatarDialog.setContentView(mAvatarView)
        (mAvatarView.parent as View).setBackgroundColor(resources.getColor(android.R.color.transparent))
        mAvatarView.tv_dialog_close.setOnClickListener { mAvatarDialog.dismiss() }
        mAvatarAdapter.setOnItemClickListener { adapter, view, position ->
            mAvatarDialog.dismiss()
            when (position) {
                1 -> {
                    PictureSelector.create(this)
                            .openCamera(PictureMimeType.ofImage())
                            .theme(R.style.picture_default_style)
                            .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                            .previewImage(true)// 是否可预览图片
                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                            .enableCrop(true)// 是否裁剪
                            .compress(true)// 是否压缩
                            .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                            .isGif(false)// 是否显示gif图片
                            .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                            .forResult(PictureConfig.CHOOSE_REQUEST)
                }
                0 -> {
                    PictureSelector.create(this)
                            .openGallery(PictureMimeType.ofImage())
                            .theme(R.style.picture_default_style)
                            .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                            .previewImage(true)// 是否可预览图片
                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                            .isCamera(false)
                            .enableCrop(true)// 是否裁剪
                            .compress(true)// 是否压缩
                            //                        .cropCompressQuality(2)
                            .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                            .isGif(false)// 是否显示gif图片
                            .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                            .scaleEnabled(true)
                            .forResult(PictureConfig.CHOOSE_REQUEST)//结果回调onActivityResult code
                }
            }

        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == -1) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data)
                    for (i in selectList.indices) {
                        val url = selectList.get(i).getCompressPath()
                        mPresenter?.uploadAvatar(url)
                    }
                }
            }
        }
    }
    

    private fun initBottomSexDialog() {
        var view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_sheet_label, null, false)
        view.recycler_view.addItemDecoration(DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(dp2px(4)))
        view.tv_title.text = "修改性别"
        mGenderAdapter.bindToRecyclerView(view.recycler_view)
        var arrayAvatar = arrayOf("男", "女")
        mGenderAdapter.setNewData(arrayAvatar.toList())
        mGenderDialog.setContentView(view)
        (view.parent as View).setBackgroundColor(resources.getColor(android.R.color.transparent))
        view.tv_dialog_close.setOnClickListener { mGenderDialog.dismiss() }
        mGenderAdapter.setOnItemClickListener { adapter, view, position ->
            mPresenter?.updateGender(position + 1)
            mGenderDialog.dismiss()
        }

    }

    private fun initDatePicker() {
        //时间选择器
        timePickerView = TimePickerBuilder(this, this)
                .setType(booleanArrayOf(true, true, true, false, false, false))// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(17)//标题文字大小
                .setTitleText("选择生日")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(0xFFA22217.toInt())//确定按钮文字颜色
                .setCancelColor(0xFFA22217.toInt())//取消按钮文字颜色
                .setTitleBgColor(0xFFFFFFFF.toInt())//标题背景颜色 Night mode
                .setBgColor(0xFFf6f6f6.toInt())//滚轮背景颜色 Night mode
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setRangDate(null, Calendar.getInstance())
                .build()

    }

}
